package virtualinit;

import virtualinit.util.CommonUtil;
import virtualinit.util.JdbcUtil;
import virtualinit.util.Log;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

//@SpringBootApplication
public class Run {
    static Log log = Log.instance;

    public enum RunType {
        virtual, channel, clean_table
    }

    static Config config = Config.instance;

    public static void main(String[] args) throws Exception {
        String runType = config.getProperty("runType");
        switch (RunType.valueOf(runType.toLowerCase())) {
            case channel:
                runChannelStoreRel();
                break;
            case virtual:
                runVirtualStock();
                break;
            case clean_table:
                cleanTable();
        }
    }

    private static void cleanTable() {
        int count = 0;
        config.initDs(1);
        config.initDbToDs();
        String cleaTables = config.getProperty(Config.configPrefix + "cleaTables");
        if (cleaTables == null && cleaTables.trim().length() == 0) {
            throw new RuntimeException("cleaTables=null");
        }

        String[] tables = cleaTables.split(",");
        List<String> collect = Arrays.stream(tables).distinct().collect(Collectors.toList());
        for (String table : collect) {
            table = table.replace("`", "").trim();
            String[] split = table.split("\\.");
            if (split.length < 2) continue;
            String db = split[0].trim();
            String tb = split[1].trim();
            List<String> tbs = CommonUtil.wrapList(tb);
            if (tb.contains("${")) {
                int idx = tb.indexOf("${");
                String tb_ = tb.substring(0, idx);
                int idxEnd = tb.indexOf("}", idx);
                String[] arr = tb.substring(idx + 2, idxEnd).split("-");
                int start = Integer.parseInt(arr[0]);
                int end = Integer.parseInt(arr[1]);

                tbs.clear();
                for (int i = start; i <= end; i++) {
                    tbs.add(tb_ + i);
                }

            }

            for (String tb_real : tbs) {
                // 拿到数据源
                Ds ds = config.dbNameToDs.get(db);
                if (ds == null) {
                    log.error("数据库：‘{}’ 不存在", db);
                    break;
                }
                String sql = "truncate table " + '`' + db + "`." + tb_real;
                try {
                    JdbcUtil.update(ds.peekConnection(), sql);
                    count ++;
                } catch (Exception e) {
                    if (e.getMessage() != null && e.getMessage().contains("doesn't exist"))
                        log.error("清空表失败：表不存在：{} 数据源信息：dsName:{} username:{} host:{}", db + "." + tb_real,
                                ds.name, ds.username, JdbcUtil.getHostPortFromUrl(ds.url));
                    else throw new RuntimeException(e);
                }
                log.info("清空表{}成功, 数据源：dsName={} username={} url={}", '`' + db + "`." + tb_real, ds.name,
                        ds.username, JdbcUtil.getHostPortFromUrl(ds.url));
            }

        }
        System.out.println();
        log.info("清空表完成，共清空{}张",count);

    }

    private static void runChannelStoreRel() throws Exception {
        config.nameToDs.values().forEach(e -> e.init(2));
        ChannelStoreRelationInit init = new ChannelStoreRelationInit();
        init.start();
        init.finish();
    }

    private static void runVirtualStock() {
        try {

            String property = config.getProperty("config.onlyB2c");
            if (property==null || !Boolean.parseBoolean(property)) {
                O2oInit o2oInit = new O2oInit();
                o2oInit.start();
                o2oInit.finish();
            }


            B2cInit b2cInit = new B2cInit();
            b2cInit.start();
            b2cInit.finish();
        } catch (Exception e) {
            log.error("发生错误退出程序：" + e.getMessage(), e);
            System.exit(1);
        }
        System.out.println("同步完成，退出程序...");
    }


}
